<?php
/**
 * 
 * @author Allen
 * @uses 用户
 * @date 2015-10-20
 *
 */
class User extends WX_Controller{
   protected $self = null;
   
   public function __construct()
	{
		parent::__construct();
		$this->load->model('user_model');
		$this->self = $this->user_model->checkUser(array("id"=>$this->user['id']));
		$this->self['areas'] = unserialize($this->self['areas']);
		$this->self['area_no'] = explode(',', $this->self['areas']['area_no']);
	}
	//个人中心
	//create by chenqi
	public function index() {	
		$this->load->model('user_code_model');
		$code_info = $this->user_code_model->checkUsercode(array("user_id"=>$this->user['id']));		
		$this->assign("code_info" , $code_info); //用户抽奖码信息
		$this->assign("user",$this->self);
		$this->display('/wap/user');

	}
	
	//个人信息
	//create by chenqi
	public function info(){
		$this->assign("user",$this->self);
		$this->display('/wap/user_info');

	}
	//保存个人信息
	//create by chenqi
	public function edit(){
		$user_data['username'] = $username = $this->input->post("username");//姓名
		$prov = $this->input->post("prov");//省代码
		$city = $this->input->post("city");//市代码
		$dist = $this->input->post("dist");//区代码
		$prov_txt = $this->input->post("prov_txt");//省文字
		$city_txt = $this->input->post("city_txt");//市文字
		$dist_txt = $this->input->post("dist_txt");//区文字
		$areas = array("area_no"=>$prov.",".$city.",".$dist,"detail"=>$prov_txt.$city_txt.$dist_txt);
		$user_data['areas'] = serialize($areas);
		$user_data['address'] = $address = $this->input->post("address");//地址
		$user_data['phone'] = $phone= $this->input->post("phone");//手机号
		$refer = "http://".$_SERVER['HTTP_HOST']."/wap/user";
		$res = array("status"=>false,"refer"=>$refer,"msg"=>"保存失败");
		if($this->user_model->editUser(array("id"=>$this->user['id']),$user_data)){
			$res = array("status"=>true,"refer"=>$refer,"msg"=>"保存成功");
		}
		$this->response($res);
	}

	//我的订单
	public function order(){
		$this->load->model('appoint_model');
		$user_order = $this->appoint_model->appointUser(array('appoint.user_id' => $this->user['id'],"data_status" =>1));
		foreach($user_order as $k => $v) {
			if($v['appoint_status'] == 1) {
				$user_order[$k]['pay_now'] = '未付款';
			}else if($v['appoint_status'] == 2) {
				$user_order[$k]['pay_now'] = '已付款';				
			}
		}	
		$this->assign('user_order',$user_order);
		$this->display('/wap/user_order');
	}
	//我的车辆

	//create by chenqi
	public function car(){
		$this->load->model('vehicle_model');
		$mycar = $this->vehicle_model->getVehicleList(array("user_id"=>$this->user['id'],"vehicle.status" =>1));
		$this->assign("cars",$mycar);
		$this->display('/wap/user_car');
	}

	//抽奖信息

	//create by chenqi
	public function award(){
		$this->load->model('user_code_model');
		$this->load->model('lottery_set_model');
		$rule = $this->lottery_set_model->checkSet();
		$winner = $this->user_code_model->getUsercodeList(array("user_code.win_status"=>1),20,0);		
		foreach($winner as $k => $v) {
			$winner[$k]['phone'] = substr_replace($v['phone'],'*****',3,5); ; 
		}
		$this->assign("rule",$rule);
		$this->assign("winner",$winner);
		$this->display('/wap/user_award');
	}
	
	//首页会员车辆报价
	public function user_quote() {
		$data = $_POST;
		$data['car_num'] = $data['car_area'].$data['car_num'];
		$this->load->model("vehicle_model");
		$vehicle_info = $this->vehicle_model->checkVehicle(array("user_id"=>$this->user['id'],"car_num"=>$data['car_num']));
		if($vehicle_info) {
			$veicle_id = $vehicle_info['id'];
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/offer/info?id=".$veicle_id;
		}else {
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/user/add_hand?car_num=".$data['car_num']."&vehicle_owner=".$data['vehicle_owner'];
		}
		exit($this->response(array('status'=>true,'refer'=>$refer)));		
	}
	//添加车辆
	public function add_hand() {
		$this->load->model('user_model');
		$this->load->model('company_model');
		$data = $_GET;
		$company_list = $this->company_model->getInsureAll();
		$this->assign("company_list",$company_list);
		$this->assign("data",$data);
		$this->display('/wap/add_hand');
	}
	
	//提交添加的车辆信息
	public function add_vehicle() {
		$data = $_POST;
		
		//上传行驶证
		if(isset($data['lic_pic'])){
			if(strpos($data['lic_pic'], 'base64')) {
				$lic_path = $this->uploadPic($data['lic_pic'],$data['lic_filetype']);  //用户上传了图才执行
				if(!$lic_path){exit($this->response(array('status'=>false,'msg'=>'图片上传失败！'))); }
				$data['licence_image'] = $lic_path;
				unset($data['lic_pic']);
				unset($data['lic_filetype']);
			}
		}
		//上传身份证
		if(isset($data['card_pic'])){
			if(strpos($data['card_pic'], 'base64')) {
				$card_path = $this->uploadPic($data['card_pic'],$data['card_filetype']);  //用户上传了图才执行
				if(!$card_path){exit($this->response(array('status'=>false,'msg'=>'图片上传失败！'))); }
				$data['card_image'] = $card_path;
				unset($data['card_pic']);
				unset($data['card_filetype']);
			}
		}

		$data['user_id'] = $this->user['id'];
		$data['create_time'] = $data['update_time'] = time();
		$this->load->model("vehicle_model");
		$check_vehicle = $this->vehicle_model->checkVehicle(array("vehicle.user_id" => $this->user['id'],"car_num" =>$data['car_num']));
		if($check_vehicle) {
			$status = true;
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/user/car";
			$msg = "请勿重复添加车辆";
			exit($this->response(array('status'=>$status,'refer'=>$refer,'msg'=>$msg)));
			
		}
		$add_vehicle = $this->vehicle_model->addVehicle($data);
		if($add_vehicle) {
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/user/vehicle_insurance?vehicle_id=".$add_vehicle;
		}else {
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/user/add_hand?car_num=".$data['car_num']."&vehicle_owner=".$data['vehicle_owner'];
		}
		exit($this->response(array('status'=>true,'refer'=>$refer)));
	}
	
	//车辆投保	
	//create by Allen
	public function vehicle_insurance() {
		$vehicle_id = $_GET['vehicle_id']; //车辆id
		$this->load->model('version_model');
		$this->load->model('insurance_model');
		$version_list = $this->version_model->getVersionAll(array("status" =>1));
		foreach($version_list as $key => $value) {
			$insurance_where['version_id like'] =  '%'.trim($value['id']).',%';
			$insurance_list = $this->insurance_model->getInsuranceAll($insurance_where);
			//echo $this->db->last_query();
			foreach($insurance_list as $k => $v) {
				$insurance_list[$k]['sum_list'] = unserialize($v['sum_list']);
			}
			$version_list[$key]['insurance_list'] = $insurance_list;
		}
		$this->assign("vehicle_id",$vehicle_id);
		$this->assign("version_list",$version_list);
		$this->display('/wap/insurance');
	}
	
	//会员报价
	public function user_offer() {
		$data = $_POST;
		$sum = $data['sum'];
		$sum_array = array();
		$sum_array = explode(":",$sum);
		$sum_list = array_filter($sum_array);
		$id_list = array_filter(explode(',', $data['id_list']));
		$array = array();
		foreach($sum_list as $key => $value) {
			$info = explode(',', $value);
			$id = $info[0];
			$array['id'][] = $info[0];
			if(in_array($id, $id_list)) {
				$array['sum'][] = $info[1];
			}else {
				$array['sum'][] = 0;
			}
		}
		unset($data['sum']);unset($data['id_list']);
		$data['offer'] = serialize($array);
		//判断车辆是否是此会员的
		$this->load->model("vehicle_model");
		$vehicle_info = $this->vehicle_model->checkVehicle(array("user_id"=>$this->user['id'],"vehicle.id"=>$data['vehicle_id']));
		if(!$vehicle_info) {
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/home/";
			exit($this->response(array('status'=>true,'refer'=>$refer,'msg'=>'车辆信息错误')));
		}
		//判断车辆是否已报价过
		$this->load->model("quote_model");
		$data['user_id'] = $this->user['id']; //会员id
//		$quote_info = $this->quote_model->checkQuote(array("quote.vehicle_id" =>$data['vehicle_id'],"quote.user_id" =>$data['user_id']));
//		if($quote_info) {
			$offer_operate = $this->quote_model->editQuote(array("vehicle_id" =>$data['vehicle_id']),$data);
//		}else {
			$offer_operate = $this->quote_model->addQuote($data);
//		}
		if($offer_operate) {
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/user/car";
			$msg ="操作成功，请等待";
		}else {
			$refer = $refer = "http://".$_SERVER['HTTP_HOST']."/wap/home";
			$msg ="操作失败，请重试";
		}
		exit($this->response(array('status'=>true,'refer'=>$refer,'msg'=>$msg)));
	}
	
	//添加抽奖码
	public function user_code() {
		$this->load->model('code_model');
		$this->load->model('user_code_model');
		$this->load->model('lottery_set_model');
		//判断是否允许抽奖
		$check_result = $this->lottery_set_model->checkSet(array("status" => 1,"start_time <" => time(),"end_time >=" => (time()-60*60*24)));
		if($check_result) {		
			$user_id = $this->user['id'];
			$rand_num = $this->code_model->checkCode();
			$usercode_data['code_id'] = $rand_num['code_id'];
			$usercode_data['user_id'] = $user_id;
			$usercode_data['create_time'] = $usercode_data['update_time'] = time();
			$insert_code = $this->user_code_model->addUsercode($usercode_data);
			if($insert_code) {
				$code_data['status'] = 0;
				$code_data['update_time'] = time();
				$edit_result = $this->code_model->editCode(array("id" =>$rand_num['id']),$code_data);
			}			
		}else {
			$msg = "活动日期已截至，请关注下次活动";
			$go_url = "/wap/user";
			$this->location_href($msg, $go_url);
		}
		$go_url = "/wap/user";
		echo "<script>window.location.replace('$go_url');</script>";
		exit;
	}
	
	//客户服务
	public function service(){
		$this->display('/wap/service');
	}
	
	//会员提交订单
	public function user_order() {
		$data = $_POST;
		$q_id = $data["q_id"];//报价id
		$insure_id = $data["id"];//险种id
		$this->load->model("quote_model");
		$vehicle = $this->quote_model->checkQuote(array("quote.id"=>$q_id));
		$vehicle_id = $vehicle['vehicle_id']; //车辆id

		//判断是否有此车辆的订单
		$this->load->model("appoint_model");
		$appoint_info = $this->appoint_model->checkAppoint(array("appoint.user_id"=>$this->user['id'],"appoint.vehicle_id"=>$vehicle_id,"data_status" => 1));
		if($appoint_info) {
			$status = false;
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/home";
			$msg = "请勿重复提交订单";
			exit($this->response(array('status'=>$status,'refer'=>$refer,'msg'=>$msg)));
		}
		
		//判断车辆是否是此会员的
		$this->load->model("vehicle_model");
		$vehicle_info = $this->vehicle_model->checkVehicle(array("user_id"=>$this->user['id'],"vehicle.id"=>$vehicle_id));
		if(!$vehicle_info) {
			$go_url = "http://".$_SERVER['HTTP_HOST']."/wap/home";
			$msg = "车辆信息错误";
			$this->location_href($msg, $go_url);
		}
		//判断是否有此报价方案
		$quote_offer = unserialize($vehicle['quote_data']);
		$count = count($quote_offer['company_id']);
		if($count -1 < $insure_id) {
			$go_url = "http://".$_SERVER['HTTP_HOST']."/wap/home";
			$msg = "报价信息错误";
			$this->location_href($msg, $go_url);
		}
			
		
		$vehicle['quote_data'] = unserialize($vehicle['quote_data']);//保险数据
		$company = $vehicle['quote_data']['company_id'][$insure_id];//保险公司
		$this->load->model("company_model");
		$cp = $this->company_model->checkInsure(array("id"=>$company));
		
		$price = $vehicle['quote_data']['sum_id'][$insure_id];//险种价钱
		$insurance_id = $vehicle['quote_data']['insurance_id'];//险种
		
		$this->load->model("insurance_model");//险种模型
		$insurance = array();
		foreach ($insurance_id as $k => $v) {
			$insurance_info = $this->insurance_model->checkInsurance(array("id"=>$v));
			$insurance[$k]['name'] = $insurance_info['name'];
			$insurance[$k]['price'] = $price[$k];
		}
		//生成订单id
		$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
		$order_id = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
		$coupon =$vehicle['coupon'];
		$sum = array_sum($price)-$coupon;
		//拼接订单数据
		$order_data['order_id'] = $order_id;
		$order_data['user_id'] = $this->user['id'];
		$order_data['vehicle_id'] = $vehicle_id;
		$order_data['order_details'] = serialize($insurance);
		$order_data['company_name'] = $cp['company_name'];
		$order_data['total_price'] = array_sum($price);
		$order_data['real_total'] = $sum;
		$order_data['coupon_price'] = $coupon;
		$order_data['create_time'] = $order_data['update_time'] = time();		
		
		$add_result = $this->appoint_model->addAppoint($order_data);
		if(!$add_result) {
			$refer = "http://".$_SERVER['HTTP_HOST']."/wap/user/order_det?order_id=".$add_result;
			$msg ="生成订单成功";
			$status = true;
		}else {
			$refer = "http://".$_SERVER['HTTP_HOST']."wap/offer/quote?id=".$insure_id."&q_id=".$q_id;
			$msg ="生成订单失败，请重试";
			$status = false;
		}
		exit($this->response(array('status'=>$status,'refer'=>$refer,'msg'=>$msg)));
	}
	
	//订单详情
	public function order_det(){
		
		$order_id = $this->input->get("order_id");//订单id
		$this->load->model("appoint_model");
		$appoint_info = $this->appoint_model->appointInfo(array('appoint.id' => $order_id));
		//判断订单是否属于此会员
		if($appoint_info['user_id'] != $this->user['id']) {
			$go_url = "http://".$_SERVER['HTTP_HOST']."/wap/home";
			$msg = "订单信息错误";
			$this->location_href($msg, $go_url);		
		}		
		$insure_list = unserialize($appoint_info['order_details']);
		$appoint_info['frame_num'] = substr($appoint_info['frame_num'],-6);

		$appoint_info['open_id'] = $this->user['open_id'];
		$code ="";
// 		if($appoint_info['appoint_status'] == 1){
// 			//生成微信支付代码
// 			$this->load->library('wx_pay');
// 			$code = $this->wx_pay->get_code($appoint_info);
// 		}	
      
//        $this->assign("code",$code);
		$this->assign("appoint_info",$appoint_info);
		$this->assign("insure_list",$insure_list);
		$this->display('/wap/order_det');
	}

	//支付回调链接
	public function notify_payment(){
		//echo "支付回调";
		$this->current_time = time();
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$notify_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		//如果付款成功
		if($notify_data['result_code'] == 'SUCCESS' && $notify_data['return_code'] == 'SUCCESS'){
			//完成支付交易
			$sn = explode('chexian', $notify_data['out_trade_no']);
			$id = $sn['0'];
			$this->load->model("appoint_model");
			$this->appoint_model->editAppoint(array('id' => $id),array("appoint_status"=>2));
			 
			
			//回调响应成功
			echo '<xml>
   					<return_code><![CDATA[SUCCESS]]></return_code>
   					<return_msg><![CDATA[OK]]></return_msg>
				 </xml>';
			exit;
		}
		//回调响应失败
		echo '<xml>
   				<return_code><![CDATA[FAIL]]></return_code>
   				<return_msg><![CDATA[ERROR]]></return_msg>
			  </xml>';
	}
	
	//回调函数
	//支付结果
	public function tips(){
		$status = $this->input->get("status");
		if($status == 1){
			$order_id = $this->input->get("order_id");
			$this->load->model("appoint_model");
			if($this->appoint_model->editAppoint(array('id' => $order_id),array("appoint_status"=>2))){				
				$go_url = "http://".$_SERVER['HTTP_HOST']."/wap/user/order_det?order_id=".$order_id;
				$msg = "支付成功";
				$this->location_href($msg, $go_url);
			}
		}else{
			$order_id = $this->input->get("order_id");
			$go_url = "http://".$_SERVER['HTTP_HOST']."/wap/user/order_det?order_id=".$order_id;
			$msg = "支付失败";
			$this->location_href($msg, $go_url);
		}
	}
}